<!--display 成绩对比-->
<template>
  <div class="grade-comparison">
    <div class="module-title">
      成绩对比
      <button
        class="info-btn"
        @mouseenter="showTooltip"
        @mouseleave="hideTooltip">
        <i class="el-icon-reading"></i>
      </button>
      <!-- 悬停提示框 -->
      <div
        v-show="tooltipVisible"
        class="tooltip-box"
        :style="tooltipStyle">
        {{ gradeComparisonInfoText }}
      </div>
    </div>
    <div class="chart-buttons">
      <button
        v-for="(btn, index) in chartButtons"
        :key="index"
        :class="['chart-btn', { active: activeChartIndex === index }]"
        @click="switchChart(index)"
      >
        {{ btn.label }}
      </button>
    </div>
    <div class="chart-container" ref="chartContainer"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  name: 'GradeComparison',
  data() {
    return {
      chart: null,
      activeChartIndex: 0,
      autoRotateTimer: null,
      isAutoRotating: true,
      rotationInterval: 5000, // 5秒轮换一次
      chartButtons: [
        { label: '高等数学', key: '高等数学' },
        { label: '大学物理', key: '大学物理' },
        { label: '高等代数', key: '高等代数' }
      ],
      gradeData: {},
      isLoading: false,
      // 提示框相关
      tooltipVisible: false,
      gradeComparisonInfoText: '',
      tooltipStyle: {
        position: 'absolute',
        top: '35px',
        left: '120px',
        zIndex: 1000
      }
    };
  },
  async mounted() {
    this.initChart();
    window.addEventListener('resize', this.handleResize);
    await this.loadGradeData();
    this.loadGradeComparisonInfoText();
    this.startAutoRotate();
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
    if (this.chart) {
      this.chart.dispose();
      this.chart = null;
    }
    this.stopAutoRotate();
  },
  methods: {
    initChart() {
      const container = this.$refs.chartContainer;
      if (!container) return;
      this.chart = echarts.init(container);
    },
    handleResize() {
      if (this.chart) {
        this.chart.resize();
      }
    },
    switchChart(index) {
      this.activeChartIndex = index;
      this.updateChartData();
      this.stopAutoRotate();
      setTimeout(() => {
        this.startAutoRotate();
      }, 10000);
    },
    startAutoRotate() {
      if (this.autoRotateTimer) {
        clearInterval(this.autoRotateTimer);
      }
      this.isAutoRotating = true;
      this.autoRotateTimer = setInterval(() => {
        const nextIndex = (this.activeChartIndex + 1) % this.chartButtons.length;
        this.activeChartIndex = nextIndex;
        this.updateChartData();
      }, this.rotationInterval);
    },
    stopAutoRotate() {
      if (this.autoRotateTimer) {
        clearInterval(this.autoRotateTimer);
        this.autoRotateTimer = null;
      }
      this.isAutoRotating = false;
    },
    async loadGradeData() {
      try {
        this.isLoading = true;
        const response = await this.$displayapi.getScoreComparison();
        if (!response || !response.data || !Array.isArray(response.data)) {
          throw new Error('API返回数据格式错误');
        }
        // 按subject分类
        this.gradeData = {};
        this.chartButtons.forEach(btn => {
          const subject = btn.key;
          const subjectData = response.data.filter(item => item.subject === subject);
          this.gradeData[subject] = {
            examNames: subjectData.map(item => item.examName),
            allAvg: subjectData.map(item => Number(item.allAvg) || 0),
            groupOne: subjectData.map(item => Number(item.groupOneAavg) || 0),
            groupTwo: subjectData.map(item => Number(item.groupTwoAavg) || 0),
            groupThree: subjectData.map(item => Number(item.groupThreeAavg) || 0)
          };
        });
        this.updateChartData();
      } catch (error) {
        console.error('成绩数据加载失败:', error);
        this.$message && this.$message.error('加载成绩数据失败');
      } finally {
        this.isLoading = false;
      }
    },
    updateChartData() {
      if (!this.chart || this.isLoading) return;
      const currentButton = this.chartButtons[this.activeChartIndex];
      const currentSubject = currentButton.key;
      const subjectData = this.gradeData[currentSubject] || { examNames: [], allAvg: [], groupOne: [], groupTwo: [], groupThree: [] };
      // 计算所有数据的最小值和最大值
      const allData = [
        ...subjectData.allAvg,
        ...subjectData.groupOne,
        ...subjectData.groupTwo,
        ...subjectData.groupThree
      ].filter(v => typeof v === 'number' && !isNaN(v));
      let minValue = 0, maxValue = 100, interval = 5;
      if (allData.length > 0) {
        minValue = Math.min(...allData);
        maxValue = Math.max(...allData);
        const range = maxValue - minValue;
        if (range <= 10) {
          interval = 2;
        } else if (range <= 20) {
          interval = 5;
        } else {
          interval = 10;
        }
        minValue = Math.floor(minValue / interval) * interval;
        maxValue = Math.ceil(maxValue / interval) * interval;
      }
      const option = {
        backgroundColor: 'transparent',
        title: {
          text: `${currentSubject}成绩对比`,
          textStyle: { color: '#d3d6dd', fontSize: 16 },
          left: 'center',
          top: 10
        },
        tooltip: {
          trigger: 'axis',
          formatter: params => {
            let result = params[0]?.name + '<br/>';
            params.forEach(param => {
              result += `<span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${param.color};"></span>`;
              result += `${param.seriesName}: ${param.value}分<br/>`;
            });
            return result;
          }
        },
        legend: {
          data: ['总平均', '一组', '二组', '三组'],
          textStyle: { color: '#d3d6dd' },
          top: 40
        },
        grid: {
          left: '3%', right: '4%', bottom: '3%', top: '25%', containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: subjectData.examNames,
          axisLine: { lineStyle: { color: '#d3d6dd' } },
          axisLabel: { interval: 0, rotate: 30 }
        },
        yAxis: {
          type: 'value',
          min: minValue,
          max: maxValue,
          interval: interval,
          axisLine: { lineStyle: { color: '#d3d6dd' } },
          splitLine: { lineStyle: { color: 'rgba(211, 214, 221, 0.1)' } },
          axisLabel: {
            color: '#d3d6dd',
            formatter: function(value) {
              return value.toFixed(1);
            }
          }
        },
        series: [
          {
            name: '总平均',
            type: 'line',
            data: subjectData.allAvg,
            smooth: true,
            lineStyle: { width: 3, color: '#4992ff' },
            itemStyle: { color: '#4992ff' }
          },
          {
            name: '一组',
            type: 'line',
            data: subjectData.groupOne,
            smooth: true,
            lineStyle: { width: 3, color: '#7cffb2' },
            itemStyle: { color: '#7cffb2' }
          },
          {
            name: '二组',
            type: 'line',
            data: subjectData.groupTwo,
            smooth: true,
            lineStyle: { width: 3, color: '#fddd60' },
            itemStyle: { color: '#fddd60' }
          },
          {
            name: '三组',
            type: 'line',
            data: subjectData.groupThree,
            smooth: true,
            lineStyle: { width: 3, color: '#ff6e76' },
            itemStyle: { color: '#ff6e76' }
          }
        ]
      };
      this.chart.setOption(option, true);
    },

    // 加载成绩对比说明文本
    async loadGradeComparisonInfoText() {
      try {
        const response = await fetch('/tltl.txt');
        if (response.ok) {
          const text = await response.text();
          // 提取"2、"后面的文本，直到下一个序号或文件结束
          const regex = /2、(.*?)(?=\s*\d+、|$)/s;
          const match = text.match(regex);
          if (match && match[1]) {
            this.gradeComparisonInfoText = match[1].trim();
            console.log('成绩对比说明文本:', this.gradeComparisonInfoText);
          } else {
            console.error('未找到成绩对比说明文本');
            this.gradeComparisonInfoText = '第四十八条 军队院校实行学员综合素质考核和全程筛选制度。院校应当对学员的思想政治、科学文化、军事专业、领导管理和身体心理等方面的综合素质进行定期考核，不合格的按照有关规定处理。第四十九条 学员在规定的修业年限内，学完教学计划规定的全部课程或者修满相应的学分，经考核合格的，准予毕业;未达到毕业条件的，作结业或者肄业处理。';
          }
        } else {
          console.error('加载成绩对比说明文本失败');
          this.gradeComparisonInfoText = '第四十八条 军队院校实行学员综合素质考核和全程筛选制度。院校应当对学员的思想政治、科学文化、军事专业、领导管理和身体心理等方面的综合素质进行定期考核，不合格的按照有关规定处理。第四十九条 学员在规定的修业年限内，学完教学计划规定的全部课程或者修满相应的学分，经考核合格的，准予毕业;未达到毕业条件的，作结业或者肄业处理。';
        }
      } catch (error) {
        console.error('加载成绩对比说明文本出错:', error);
        this.gradeComparisonInfoText = '第四十八条 军队院校实行学员综合素质考核和全程筛选制度。院校应当对学员的思想政治、科学文化、军事专业、领导管理和身体心理等方面的综合素质进行定期考核，不合格的按照有关规定处理。第四十九条 学员在规定的修业年限内，学完教学计划规定的全部课程或者修满相应的学分，经考核合格的，准予毕业;未达到毕业条件的，作结业或者肄业处理。';
      }
    },

    // 显示提示框
    showTooltip() {
      this.tooltipVisible = true;
    },

    // 隐藏提示框
    hideTooltip() {
      this.tooltipVisible = false;
    }
  }
};
</script>

<style lang="scss" scoped>
.grade-comparison {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;

  .module-title {
    font-size: 22px;
    color: #68d8fe;
    margin-bottom: 15px;
    margin-top: 10px;
    margin-left: 20px;
    font-weight: bold;
    position: relative;
    z-index: 1;
    display: flex;
    align-items: center;
    gap: 10px;

    .info-btn {
      background: rgba(104, 216, 254, 0.2);
      border: 1px solid rgba(104, 216, 254, 0.5);
      border-radius: 4px;
      color: #68d8fe;
      cursor: pointer;
      padding: 4px 8px;
      font-size: 16px;
      transition: all 0.3s ease;
      display: flex;
      align-items: center;
      justify-content: center;

      &:hover {
        background: rgba(104, 216, 254, 0.3);
        border-color: rgba(104, 216, 254, 0.8);
        color: #ffffff;
        transform: scale(1.05);
      }

      i {
        font-size: 14px;
      }
    }

    .tooltip-box {
      background: rgba(19, 25, 47, 0.95);
      border: 1px solid rgba(104, 216, 254, 0.5);
      border-radius: 6px;
      padding: 12px 16px;
      color: #d3d6dd;
      font-size: 18px;
      line-height: 1.6;
      max-width: 350px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
      backdrop-filter: blur(10px);
      word-wrap: break-word;
      white-space: normal;

      &::before {
        content: '';
        position: absolute;
        top: -6px;
        left: 20px;
        width: 0;
        height: 0;
        border-left: 6px solid transparent;
        border-right: 6px solid transparent;
        border-bottom: 6px solid rgba(104, 216, 254, 0.5);
      }

      &::after {
        content: '';
        position: absolute;
        top: -5px;
        left: 21px;
        width: 0;
        height: 0;
        border-left: 5px solid transparent;
        border-right: 5px solid transparent;
        border-bottom: 5px solid rgba(19, 25, 47, 0.95);
      }
    }
  }

  .chart-buttons {
    display: flex;
    margin-bottom: 15px;
    margin-left: 20px;

    .chart-btn {
      background-color: rgba(19, 25, 47, 0.6);
      border: 1px solid rgba(104, 216, 254, 0.3);
      color: #d3d6dd;
      padding: 6px 12px;
      margin-right: 10px;
      border-radius: 4px;
      cursor: pointer;
      transition: all 0.3s ease;
      outline: none;
      font-size: 18px;

      &:hover {
        background-color: rgba(104, 216, 254, 0.1);
      }

      &.active {
        background-color: rgba(104, 216, 254, 0.2);
        border-color: #68d8fe;
        color: #68d8fe;
      }
    }
  }

  .chart-container {
    flex: 1;
    width: 100%;
    height: calc(100% - 90px);
    min-height: 250px;
  }
}
</style>
